// 主应用逻辑
document.addEventListener('DOMContentLoaded', function () {
    const noteForm = document.getElementById('noteForm');
    const notesList = document.getElementById('notesList');

    // 初始化应用
    renderNotes();

    // 表单提交事件
    noteForm.addEventListener('submit', function (e) {
        e.preventDefault();

        const title = document.getElementById('noteTitle').value;
        const content = document.getElementById('noteContent').value;

        if (title && content) {
            addNewNote(title, content);
            noteForm.reset();
        }
    });

    // 添加新笔记
    async function addNewNote(title, content) {
        // const notes = getNotesFromLocalStorage();
        // const newNote = {
        //     id: getRandomId(),
        //     title,
        //     content,
        //     likes: 0,
        //     createdAt: new Date().toISOString(),
        //     likedByUser: false
        // };

        // notes.unshift(newNote); // 添加到数组开头
        // saveNotesToLocalStorage(notes);//保存
        renderNotes();//读取

        // await fetch('http://127.0.0.1:8080/auth/test')

        //     .then(response => {
        //         if (!response.ok) {
        //             throw new Error('网络响应不正常');
        //         }
        //         return response;
        //     })
        //     .then(data => console.log(data))
        //     .catch(error => console.error('请求错误:', error));

        // const data = await fetch('http://127.0.0.1:8080/auth/test', {
        //     mode: 'cors', // 明确请求模式
        //     headers: {
        //         'Content-Type': 'application/json'
        //     }
        // })
        //     .then(response => response.json())
        //     .then(data => {
        //         // console.log(data);
        //         return data;
        //     }
        //     )
        //     .catch(error => console.error('Error:', error));

        const data = await fetch(`http://localhost/api/note/publish?title=${title}&text=${content}`, {
            mode: 'cors', // 明确请求模式
            headers: {
                'Content-Type': 'application/json'
            }
        })
            .then(response => response.json())
            .then(data => {
                // console.log(data);
                return data;
            }
            )
            .catch(error => console.error('Error:', error));
        renderNotes();
    }

    // 渲染所有笔记
    async function renderNotes() {
        //获取所有笔记信息
        const data = await fetch(`http://localhost/api/note/list`, {
            mode: 'cors', // 明确请求模式
            headers: {
                'Content-Type': 'application/json'
            }
        })
            .then(response => response.json())
            .then(data => {
                // console.log(data);
                return data;
            }
            )
            .catch(error => console.error('Error:', error));


        // const notes = getNotesFromLocalStorage();
        notesList.innerHTML = '';

        if (data.data.length === 0) {
            notesList.innerHTML = '<p class="no-notes">还没有笔记，发布你的第一条笔记吧！</p>';
            return;
        }

        // notes.forEach(note => {
        //     const noteElement = createNoteElement(note);


        //     notesList.appendChild(noteElement);
        // });

        //将数据转换成笔记
        data.data.forEach(note => {
            const noteElement = createNoteElement(note);

            notesList.appendChild(noteElement);
        });

    }

    // 创建单个笔记元素
    function createNoteElement(note) {
        const noteCard = document.createElement('div');
        noteCard.className = 'note-card';
        noteCard.dataset.id = note.id;


        let showText =
            `<button class="delete-btn" title="删除笔记">×</button>
            <h2>作者：<a href='myCraft.html?uid=${note.userId}' style='text-decoration: none; color: green;' >${note.username}</a></h2>
            <h3>${note.title}</h3>
            <p>${note.content}</p>
            <div class="note-meta">
                <span>${formatDate(note.createdAt)}</span>`;

        if (note.likedNames != null)
            showText += `<span> 点赞者：${note.likedNames}</span >`;

        showText += `<button class="like-btn ${note.likedByUser ? 'liked' : ''}">
                    <span class="like-count">${note.likeCount}</span> 点赞
                </button>
            </div>`;
        // console.log(showText);

        noteCard.innerHTML = showText;

        // 添加点赞事件
        const likeBtn = noteCard.querySelector('.like-btn');
        likeBtn.addEventListener('click', () => toggleLike(note.id));

        // 添加删除事件
        const deleteBtn = noteCard.querySelector('.delete-btn');
        deleteBtn.addEventListener('click', () => deleteNote(note.id));

        return noteCard;
    }

    // 切换点赞状态
    async function toggleLike(noteId) {
        //查询是否点赞过
        const data = await fetch(`http://localhost/api/note/liked?noteId=${noteId}`, {
            mode: 'cors', // 明确请求模式
            headers: {
                'Content-Type': 'application/json'
            }
        })
            .then(response => response.json())
            .then(data => {
                // console.log(data);
                return data;
            }
            )
            .catch(error => console.error('Error:', error));
        if (data.code == 200) {

            // console.log('noteId', noteId);
            const list = document.getElementById('notesList')
            const childDivs = list.querySelectorAll('.note-card'); // 获取所有子 div
            for (i = 0; i < childDivs.length; i++) {
                // console.log(childDivs[i].dataset.id);

                if (childDivs[i].dataset.id == noteId) {
                    break;
                }
            }
            let btn = childDivs[i].getElementsByClassName('note-meta')[0].getElementsByClassName('like-btn')[0]
            const count = btn.getElementsByClassName('like-count')[0]
            //获取类名
            if (data.data.likedByUser) {
                // console.log(btn)
                btn.className = 'like-btn liked'
                // count.getHTML
                count.innerHTML = Number(count.textContent) + 1
                // console.log(count.textContent);
            }
            else {
                btn.className = 'like-btn'
                count.innerHTML = count.textContent - 1
            }

            // note.likes = note.likedByUser ? note.likes + 1 : note.likes - 1;
            renderNotes();
        }

    }

    // 删除笔记
    async function deleteNote(noteId) {
        if (confirm('确定要删除这条笔记吗？')) {
            // const notes = getNotesFromLocalStorage();
            // const updatedNotes = notes.filter(note => note.id !== noteId);
            // saveNotesToLocalStorage(updatedNotes);

            const data = await fetch(`http://localhost/api/note/del?noteId=${noteId}`, {
                mode: 'cors', // 明确请求模式
                headers: {
                    'Content-Type': 'application/json'
                }
            })
                .then(response => response.json())
                .then(data => {
                    console.log(data);
                    return data;
                }
                )
                .catch(error => console.error('Error:', error));

            renderNotes();
        }
    }
});